﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Collections;
using Fcdbas.CodeBuilder;
using Fcdbas.CodeBuilder.TemplateCode;
using System.Linq;
using Fcdbas.Common.File;
namespace Fcdbas.Tool
{
    public partial class CodeBuilder : Form
    {
        private static readonly string StringFormat = "Uppercase,Lowercase,Invisble,Unformatted";
        private static readonly string NumberFormat = "Percentage,Currency,Invisible,Decimal,Unformatted";
        private static readonly string DateFormat = "Date,DateTime,Time,Unformatted";

        private static readonly string cdbFile = AppDomain.CurrentDomain.BaseDirectory + "Template\\template.cdb";
        private static readonly string pkgFile = AppDomain.CurrentDomain.BaseDirectory + "Template\\template.pkg";
        private static readonly string rptFile = AppDomain.CurrentDomain.BaseDirectory + "Template\\template.rpt";
        private static readonly string webFile = AppDomain.CurrentDomain.BaseDirectory + "Template\\template.web";
        private static readonly string bssFile = AppDomain.CurrentDomain.BaseDirectory + "Template\\template.bss";
        private string projectpath;
        public string ProjectPath
        {
            get
            {
                if (projectpath == AppDomain.CurrentDomain.BaseDirectory && CurProject != null)
                    projectpath = projectpath + CurProject.Name;
                return projectpath;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                    projectpath = value;
            }
        }
        public CodeBuilder()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CodeBuilder_Load(object sender, EventArgs e)
        {
            ProjectPath = AppDomain.CurrentDomain.BaseDirectory;
            this.logicUnit = new Fcdbas.CodeBuilder.TemplateCode.LogicUnit();
            this.modelBS.DataSource = logicUnit;
            logicUnit.FieldList = new List<Fcdbas.CodeBuilder.TemplateCode.FieldStutrc>();
            this.modelView.DataSource = logicUnit.FieldList;
            //this.modelView.AddNew();
            this.modelView.AllowNew = true;
            this.modelView.AddNew();
            this.gridControl1.DataSource = this.modelView;
            //this.gridControl1.DefaultView
            ((FieldStutrc)modelView.Current).DataType = "String";

            string[] s1 = StringFormat.Split(',');
            foreach (string ss in s1)
            {
                this.repositoryItemComboBoxFormat.Items.Add(ss);
            }
        }



        #region 定義的方法  
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="file_path">文件路径</param>
        /// <param name="text">文件内容</param>
        /// <param name="extend_name">文件后缀名</param>
        private void CreateFile(string file_path,string text,string extend_name )
        {
            //string extend_name = ".CDB";
            //string text = "";
            if (Path.GetExtension(file_path) != extend_name)
            {
                file_path += extend_name;
            }

            string directory_path = Path.GetDirectoryName(file_path);
            if (!Directory.Exists(directory_path))
            {
                Directory.CreateDirectory(directory_path);
            }

            FileStream fs = new FileStream(file_path, FileMode.Create, FileAccess.Write);

            StreamWriter sw = new StreamWriter(fs);

            sw.Write(text);
            sw.Flush();

            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// 项目数据位置
        /// </summary>
        /// <param name="projectFilePath"></param>
        void InitTreeData(string projectFilePath)
        {
            string _projectStrContent =  Fcdbas.Core.Util.FileHelper.GetFileContent(projectFilePath);
            //Project project = Fcbbas.CodeBuilder.JsonSerializer<Project>.JsonToDataContract(_projectStrContent);
            Project project = Fcbbas.CodeBuilder.JsonSerializer<Project>.JSonToObject<Project>(_projectStrContent);
            CurProject = project;
            this.ProjectName = project.Name;
            InitTreeData(project);
        }

        void InitTreeData(Project project)
        {
            //TreeNode mainNode = this.treeView1.Nodes[0];
            treeView1.Nodes.Clear();
            TreeNode rootNode = treeView1.Nodes.Insert(0, project.Name, project.Name);
            InitTreeModuleData(project.Model, rootNode);
        }

        void InitTreeModuleData(IList<Moudle> models, TreeNode rootNode)
        {
            foreach (Moudle _model in models)
            {
                var shpordNode = rootNode.Nodes.Insert(0, _model.Id, _model.Id);
                var modelNode = shpordNode.Nodes.Insert(0, "Model", "Model Propertiers");
                InitTreeLUData(_model.LogicUnit, modelNode, false);
                var _pReportNode = shpordNode.Nodes.Insert(1, "PresentationReports", "Presentation(Reports)");
                InitTreeLUData(_model.LogicUnit, _pReportNode, false);
                var _pWebNode = shpordNode.Nodes.Insert(2, "PresentationWeb", "Presentation(Web)");
                InitTreeLUData(_model.LogicUnit, _pWebNode, false);
                var _BLWebNode = shpordNode.Nodes.Insert(3, "BusinessLogic", "Business Logic(PL/SQL)");
                InitTreeLUData(_model.LogicUnit, _BLWebNode, false);
                TreeNode _node = shpordNode.Nodes.Insert(4, "Storage(My Sql)", "Storage(My Sql)");
                //TreeNode _tableNode = _node.Nodes.Insert(0, "table", "table");
                InitTreeLUData(_model.LogicUnit, _node, false);

                //TreeNode _filesTreeNode = _node.Nodes.Insert(0, "Fies", "Files");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="LUs"></param>
        /// <param name="modelNode"></param>
        /// <param name="flag"></param>
        void InitTreeLUData(IList<LogicUnit> LUs, TreeNode modelNode,bool flag)
        {
            foreach (LogicUnit lu in LUs)
            {
                var luTreeNode = modelNode.Nodes.Insert(0, lu.LuName, lu.LuName);
                if (flag)
                {
                    luTreeNode.Nodes.Insert(0, bTableStutrcTemplate.GetUpperString(lu.LuName, "_") + "TAB", bTableStutrcTemplate.GetUpperString(lu.LuName, "_") + "TAB");
                    luTreeNode.Nodes.Insert(1, bTableStutrcTemplate.GetUpperString(lu.LuName, "_") + "PK", bTableStutrcTemplate.GetUpperString(lu.LuName, "_") + "PK");
                }
            }
        }

        //void InitTreeLUData(IList<TableStutrc> LUs, TreeNode modelNode

        /// <summary>
        /// 新项目
        /// </summary>
        public  void NewProject(string projectName)
        {
            CurProject = new Project();
            CurProject.Name = projectName;
            CurProject.Model = new List<Moudle>();
        }

        /// <summary>
        /// 新模块
        /// </summary>
        /// <param name="modelName"></param>
        void NewMoudle(string modelName)
        {
            CurModel = modelName;
            Moudle _model = new Moudle();
            _model.ProjectName = _curProject.Name;
            _model.Id = modelName;
            _model.LogicUnit = new List<LogicUnit>();
            CurProject.Model.Add(_model);
            ///CurProject.Model
        }

        /// <summary>
        /// 新逻辑单元
        /// </summary>
        /// <param name="LogicUnit"></param>
        void NewLU(string newLogicUnit)
        {
            CurLogiUnit = new LogicUnit();
            //tableStutrc.LuName = newLogicUnit;
            CurLogiUnit.LuName = newLogicUnit;
            CurLogiUnit.Package = ConverString(newLogicUnit, "_") + "_Api";
            CurLogiUnit.View = ConverString(newLogicUnit, "_");
            CurLogiUnit.TableName = ConverString(newLogicUnit, "_") + "_Tab";
            _logicUnit = CurLogiUnit;
            if (this.CurModel == null)
            {
                this.CurModel = this.treeView1.SelectedNode.Parent.Name;
            }
            Moudle _model = CurProject.Model.Where(p => p.Id == CurModel).First();
            _model.LogicUnit.Add(CurLogiUnit);
        }


        void InitProjectXMLFile()
        {
            NewProject(this.ProjectName);


            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + ProjectName +"/"+ProjectName+ ".xml"))
            {
                return;
            }
            string xmlfile=AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml";
            string directory_path = Path.GetDirectoryName(xmlfile);
            if (!Directory.Exists(directory_path))
            {
                Directory.CreateDirectory(directory_path);
            }
            XmlFile xmlFile = new XmlFile(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
               xmlFile.CreateXMLDocument("Project");

               var doc = xmlFile.GetDoc(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
               //var doc = xmlFile.GetDoc(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
               doc.DocumentElement.SetAttribute("Name", this.ProjectName);
               //var root = doc.DocumentElement;
               //root.SetAttribute("name", ProjectName);
               //ele.AppendChild(pro);
               //ele.SetAttribute("Id", "Shpord");
               //root.AppendChild(ele);
               
               //doc.AppendChild(ele);
               doc.Save(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
        }

        /// <summary>
        /// 初始化项目文件
        /// </summary>
        void InitModelXMLFile()
        {
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml"))
            {
                return;
            }
            string xmlfile = AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml";
            string directory_path = Path.GetDirectoryName(xmlfile);
            if (!Directory.Exists(directory_path))
            {
                Directory.CreateDirectory(directory_path);
            }
            XmlFile xmlFile = new XmlFile(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
            xmlFile.CreateXMLDocument("Project");
            var doc = xmlFile.GetDoc(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
            doc.DocumentElement.SetAttribute("Name", this.ProjectName);
            var ele = doc.CreateElement("Model");
            var pro = doc.CreateElement("Properties");
            var root = doc.DocumentElement;
            root.SetAttribute("name", ProjectName);
            ele.AppendChild(pro);
            ele.SetAttribute("Id", "Shpord");
            root.AppendChild(ele);

            //doc.AppendChild(ele);
            doc.Save(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
        }

        /// <summary>
        /// 生成实体XMl Node
        /// </summary>
        void CreateModelXmlNode()
        {
            string xmlfile = AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml";
            string directory_path = Path.GetDirectoryName(xmlfile);
            if (!Directory.Exists(directory_path))
            {
                Directory.CreateDirectory(directory_path);
            }
            XmlNode xmlnode = (new XmlFile(xmlfile)).LoadXml();
            XmlFile xmlFile = new XmlFile(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
            var doc = xmlFile.GetDoc(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
            var _modelNode = doc.CreateElement("Model");
            _modelNode.SetAttribute("Id", this.MoudleName);
            var pro = doc.CreateElement("Properties");
            _modelNode.AppendChild(pro);
            doc.DocumentElement.AppendChild(_modelNode);
            doc.Save(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
        }

        /// <summary>
        /// 生成逻辑单元XmlNode
        /// </summary>
        void CreateLogicUnitXmlNode()
        {
            string xmlfile = AppDomain.CurrentDomain.BaseDirectory + ProjectName+"/"+ ProjectName + ".xml";
            string directory_path = Path.GetDirectoryName(xmlfile);
            if (!Directory.Exists(directory_path))
            {
                Directory.CreateDirectory(directory_path);
            }
            XmlNode xmlnode = (new XmlFile(xmlfile)).LoadXml();
            XmlFile xmlFile = new XmlFile(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
            var doc = xmlFile.GetDoc(AppDomain.CurrentDomain.BaseDirectory + ProjectName + "/" + ProjectName + ".xml");
            var PropertiesNode = doc.DocumentElement.SelectSingleNode("Model[@Id='"+this.MoudleName+"']/Properties");
            var logicalUnitNode = doc.DocumentElement.SelectSingleNode("Model[@Id='" + this.MoudleName + "']/Properties/LogicalUnit[@LuName='" + this.logicUnit.LuName + "']");
            if (logicalUnitNode == null)
            {
                var _logicalUnitNode = doc.CreateElement("LogicalUnit");
                _logicalUnitNode.SetAttribute("LuName", this.logicUnit.LuName);
                _logicalUnitNode.SetAttribute("Package", this.logicUnit.Package);
                _logicalUnitNode.SetAttribute("View", this.logicUnit.View);
                _logicalUnitNode.SetAttribute("Table", this.logicUnit.TableName);
                PropertiesNode.AppendChild(_logicalUnitNode);
                logicalUnitNode = _logicalUnitNode;
            }
            else
            {
                logicalUnitNode.Attributes["LuName"].Value = this.MoudleName;
                logicalUnitNode.Attributes["Package"].Value = this.logicUnit.Package;
                logicalUnitNode.Attributes["View"].Value = this.logicUnit.View;
                logicalUnitNode.Attributes["Table"].Value = this.logicUnit.TableName;
            }

            foreach (XmlNode _node in logicalUnitNode.ChildNodes)
            {
                logicalUnitNode.RemoveChild(_node);
            }

            //this._tableStutrc.FieldList = new List<FieldStutrc>();
            //foreach (var a in this.modelView.DataSource)
            //{
            //}

            if (this.logicUnit.FieldList != null)
            {
                var attr = doc.CreateElement("Attribute");
                logicalUnitNode.AppendChild(attr);
                foreach (var e in this.logicUnit.FieldList)
                {
                    var _attr = doc.CreateElement("Attribute");
                    _attr.SetAttribute("Id", e.Id);
                    _attr.SetAttribute("Inserable", e.pInserable);
                    _attr.SetAttribute("Key", e.pKey);
                    _attr.SetAttribute("Length", e.Length);
                    _attr.SetAttribute("LovFlag", e.pLovFlag);
                    _attr.SetAttribute("OptionName", e.OptionName);
                    _attr.SetAttribute("ParentKeys", e.ParentKeys);
                    _attr.SetAttribute("ReferenceClass", e.ReferenceClass);
                    _attr.SetAttribute("Required", e.pRequired);
                    _attr.SetAttribute("Updateable", e.Updateable);
                    _attr.SetAttribute("Format", e.Format);
                    _attr.SetAttribute("DataType", e.DataType);
                    _attr.SetAttribute("Prompt", e.Prompt);
                    _attr.SetAttribute("Public", e.pPublic);
                    _attr.SetAttribute("OptionName", e.OptionName);
                    attr.AppendChild(_attr);
               }

            } 
            doc.Save(AppDomain.CurrentDomain.BaseDirectory + ProjectName+"/"+ProjectName + ".xml");
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="moudleName"></param>
        void NewModule(string moudleName)
        {
            NewMoudle(moudleName);

            TreeNode mainNode = this.treeView1.Nodes[0];
            var shpordNode = mainNode.Nodes.Insert(0, this.MoudleName, this.MoudleName);
            var modelNode = shpordNode.Nodes.Insert(0, "Model", "Model Propertiers");
            shpordNode.Nodes.Insert(1, "PresentationReports", "Presentation(Reports)");
            shpordNode.Nodes.Insert(2, "PresentationWeb", "Presentation(Web)");
            shpordNode.Nodes.Insert(3, "BusinessLogic", "Business Logic(PL/SQL)");
            TreeNode _node = shpordNode.Nodes.Insert(4, "Storage(My Sql)", "Storage(My Sql)");
            //TreeNode _tableNode = _node.Nodes.Insert(0, "table", "table");
        }

        void NewLogicUint(string newLogicUnit)
        {
            NewLU(newLogicUnit);
            
            logicUnit.LuName = newLogicUnit;
            logicUnit.Package = ConverString(newLogicUnit, "_") + "_Api";
            logicUnit.View = ConverString(newLogicUnit, "_");
            logicUnit.TableName = ConverString(newLogicUnit, "_") + "_Tab";

            this.txtPackage.Text = ConverString(newLogicUnit, "_");
            this.txtView.Text = ConverString(newLogicUnit, "_");
            this.txtTableName.Text = ConverString(newLogicUnit, "_") + "_Tab";

            this.modelBS.DataSource = logicUnit;


        }
        #endregion 

        #region 菜單

        /// <summary>
        /// 初始化主菜单
        /// </summary>
        void InitMainMenu()
        {
            TreeNode mainNode = this.treeView1.Nodes.Insert(0, ProjectName, ProjectName+".prj");
        }


        /// <summary>
        /// 字符轉換
        /// 將DropName轉換成Drop_Name 或Drop Name
        /// </summary>
        /// <param name="str"></param>
        /// <param name="splitStr"></param>
        /// <returns>STRING</returns>
        string ConverString(string str,string splitStr)
        {
            string _str="";
            for(int i=0;i<str.Length;i++)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(str[i].ToString(), "[A-Z]") && i != 0)
                {
                    _str = _str + splitStr;
                }
                _str = _str + str[i].ToString();
            }
            return _str;
        }



        /// <summary>
        /// 初始化主菜单
        /// </summary>
        /// <param name="projectFile">项目文件</param>
        void InitMainMenu(string projectFile)
        {
            XmlNode xmlnode = (new XmlFile(projectFile)).LoadXml();
            this.logicUnit = new LogicUnit();
            this.ProjectName = xmlnode.ParentNode.Attributes["Name"].Value;
            InitMainMenu();
            foreach (XmlNode node in xmlnode.ParentNode.ChildNodes)
            {
                var shpordNode = this.treeView1.Nodes[0].Nodes.Insert(0, node.Attributes["Id"].Value);
                //var _ModelTreeNode = shpordNode.Nodes.Insert(0, node.Attributes["Id"].Value);
                var modelNode = shpordNode.Nodes.Insert(0, "Model", "Model Propertiers");
                shpordNode.Nodes.Insert(1, "PresentationReports", "Presentation(Reports)");
                shpordNode.Nodes.Insert(2, "PresentationWeb", "Presentation(Web)");
                shpordNode.Nodes.Insert(3, "BusinessLogic", "Business Logic(PL/SQL)");
                TreeNode _node = shpordNode.Nodes.Insert(4, "Storage(My Sql)", "Storage(My Sql)");
                TreeNode _tableNode = _node.Nodes.Insert(0, "table", "table");
                foreach (XmlNode _logicUnitNode in node.ChildNodes[0].ChildNodes)
                {
                    //foreach(XmlNode _logicNode in _node.ChildNodes[0].
                }
            }
        }
        #endregion

        #region 属性
        private Project _curProject = new Project();
        public Project CurProject
        {
            get;
            set;
        }


        /// <summary>
        /// 当前模块
        /// </summary>
        public Moudle CurMoudle
        {
            get
            {
                var module = this.CurProject.Model.Where(p => p.Id == CurModel);
                return module.Count() > 0 ? module.First() : (new Moudle());
            }
        }


        /// <summary>
        /// 当前模块名称
        /// </summary>
        public string CurModel
        {
            get;
            set;
        }
        
        /// <summary>
        /// 当前CurLogiUnit
        /// </summary>
        public Fcdbas.CodeBuilder.TemplateCode.LogicUnit CurLogiUnit
        {
            get;
            set;
        }

        


        public IList<Fcdbas.CodeBuilder.TemplateCode.LogicUnit> LogicUnitLits
        {
            get;
            set;
        }


        /// <summary>
        /// 项目名称
        /// </summary>
        public string ProjectName
        {
            get;
            set;
        }


        /// <summary>
        /// 模塊名稱
        /// </summary>
         public string MoudleName
        {
            get;
            set;
        }


        /// <summary>
        /// 项目名件地址
        /// </summary>
        public string ProejctFile
        {
            get;
            set;
        }

        /// <summary>
        /// 对象结构
        /// </summary>
         private Fcdbas.CodeBuilder.TemplateCode.LogicUnit _logicUnit = new Fcdbas.CodeBuilder.TemplateCode.LogicUnit();
        public Fcdbas.CodeBuilder.TemplateCode.LogicUnit logicUnit
        {
            get
            {
                return _logicUnit;
            }
            set
            {
                _logicUnit = value;
            }
        }
        #endregion

        #region treeView 事件方法
        private void treeView1_MouseClick(object sender, MouseEventArgs e)
        {
            //if (this.treeView1.SelectedNode.Text == "Model Propertiers")
            //{
            //    if (e.Button.ToString() == "Right")
            //    {
            //        //MessageBox.Show(e.X + ":" + e.Y);
            //        this.contextMenuStrip1.Show();
            //   } 
            //}
        }


        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //var _pReportNode = shpordNode.Nodes.Insert(1, "PresentationReports", "Presentation(Reports)");
            //InitTreeLUData(_model.LogicUnit, _pReportNode, false);
            //var _pWebNode = shpordNode.Nodes.Insert(2, "PresentationWeb", "Presentation(Web)");
            //InitTreeLUData(_model.LogicUnit, _pWebNode, false);
            //var _BLWebNode = shpordNode.Nodes.Insert(3, "BusinessLogic", "Business Logic(PL/SQL)");
            //InitTreeLUData(_model.LogicUnit, _BLWebNode, false);
            //TreeNode _node = shpordNode.Nodes.Insert(4, "Storage(My Sql)", "Storage(My Sql)");
            if (e.Node.Parent != null && e.Node.Parent.Text == "Business Logic(PL/SQL)")
            {
                string module = e.Node.Parent.Parent.Text;
                string luName = e.Node.Text;
                LogicUnit lu = CurProject.Model.Where(p => p.Id == module).First().LogicUnit.Where(p => p.LuName == luName).First();
                lu.ModelName = module;

                Fcdbas.CodeBuilder.NewModPart form = new Fcdbas.CodeBuilder.NewModPart(lu,"PKG");
                form.Owner = this;
                if (DialogResult.OK == (form).ShowDialog())
                {
                    BulidCodeFile(lu, lu.PKGFile, "PKG");
                }
            }

            if (e.Node.Parent != null && e.Node.Parent.Text == "Storage(My Sql)")
            {
                string module = e.Node.Parent.Parent.Text;
                string luName = e.Node.Text;
                LogicUnit lu = CurProject.Model.Where(p => p.Id == module).First().LogicUnit.Where(p => p.LuName == luName).First();
                lu.ModelName = module;
                Fcdbas.CodeBuilder.NewModPart form = new Fcdbas.CodeBuilder.NewModPart(lu,"CDB");
                form.Owner = this;
                if (DialogResult.OK == (form).ShowDialog())
                {
                    BulidCodeFile(lu, lu.CDBFile, "CDB");
                }
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            
            if (this.treeView1.SelectedNode == null)
            {
                return;
            }




            if (e.Node.Text == "Model Propertiers")
            {
                if (e.Button.ToString() == "Right")
                {
                    this.cmsLogicUnit.Show(MousePosition);
                    this.cmsLogicUnit.Items[0].Enabled = true;
                    //this.cmsLogicUnit.Items[1].Enabled = false;
                    //this.cmsLogicUnit.Items[2].Enabled = false;
                }
                else if (e.Button.ToString() == "Left")
                {
                    this.logicUnit = null;
                }
            }

            if (e.Node.Parent!=null && e.Node.Parent.Text == "Model Propertiers")
            {
                if (e.Button.ToString() == "Right")
                {
                    //this.cmsLogicUnit.Show(MousePosition);
                    //this.cmsLogicUnit.Items[0].Enabled = false; 
                    //this.cmsLogicUnit.Items[1].Enabled = true; 
                    //this.cmsLogicUnit.Items[2].Enabled = true;
                }
                else if (e.Button.ToString() == "Left")
                {
                    this.logicUnit = null;
                }
            }



            if (e.Node.Text == ProjectName + ".prj")
            {
                if (e.Button.ToString() == "Right")
                {
                    //MessageBox.Show(e.X + ":" + e.Y);
                    this.cmsModel.Show(MousePosition);
                    //this.contextMenuStrip1.PointToScreen();
                }
            }
            ///
            ///  逻辑单元右键菜单用于保存数据
            ///
            if (e.Node.Parent != null && e.Node.Parent.Text == "Model Propertiers")
            {
                //if (e.Button.ToString() == "Right")
                {
                    //panel1.Enabled = true;
                    //this.gridControl1.Enabled = true;
                    panel1.Visible = true;
                    this.gridControl1.Visible = true;
                    Moudle moudle = CurProject.Model.Where(p => p.Id == e.Node.Parent.Parent.Name).First();
                    this.logicUnit = moudle.LogicUnit.Where(p => p.LuName == e.Node.Text).FirstOrDefault();
                    if (this.logicUnit == null)
                        this.logicUnit = new LogicUnit();
                    this.modelBS.DataSource = this.logicUnit;
                    this.modelView.DataSource = this.logicUnit.FieldList;
                }
            }
            else
            {
                this.logicUnit = new LogicUnit();
                
                this.modelBS.DataSource =this.logicUnit;
                this.modelView.DataSource = this.logicUnit.FieldList;
                //panel1.Enabled = false;
                //this.gridControl1.Enabled = false;
                panel1.Visible = false;
                this.gridControl1.Visible = false;
            }


            ///
            ///  逻辑单元右键菜单用于保存数据
            ///
            if (e.Node.Parent != null && e.Node.Parent.Text == "Model Propertiers")
            {
                //MessageBox.Show(this.treeView1.SelectedNode.Text);
                if (e.Button.ToString() == "Right")
                {
                    
                }
            }
        }

        private void newModelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Fcdbas.CodeBuilder.NewFile form = new Fcdbas.CodeBuilder.NewFile(1);
            NewModel form = new NewModel(1);
            form.Owner = this;
            if (DialogResult.OK == (form).ShowDialog())
            {
                NewModule(this.MoudleName);

            }
        }



        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Fcdbas.CodeBuilder.NewLogicUnit form = new Fcdbas.CodeBuilder.NewLogicUnit(1);
            form.Owner = this;
            if (DialogResult.OK == (form).ShowDialog())
            {
                this.treeView1.SelectedNode.Nodes.Insert(this.treeView1.SelectedNode.Nodes.Count, CurLogiUnit.TableName);
                TreeNode node = this.treeView1.SelectedNode.NextNode;
                while (node != null)
                {
                    //if (node.Text == "Storage(My Sql)")
                    //{
                    //    node = node.NextNode;
                    //    continue;
                    //}
                    node.Nodes.Insert(node.Nodes.Count, CurLogiUnit.TableName);
                    node = node.NextNode;
                }
                //CreateLogicUnitXmlNode();
                NewLogicUint(CurLogiUnit.TableName);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 其它事件
        private void openProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenProject();
        }

        /// <summary>
        /// 打开项目
        /// </summary>
        private void OpenProject()
        {
            if (this.treeView1.Nodes.Count > 0)
            {
                if (MessageBox.Show("Do you save the current project?", "Message", MessageBoxButtons.YesNo) == DialogResult.OK)
                {
                    SaveProject();
                }
                this.treeView1.Nodes.Clear();
            }


            this.oBuliderXml.Filter = "项目文件(*.prj)|*.prj";
            if (DialogResult.OK == this.oBuliderXml.ShowDialog())
            {
                string file = oBuliderXml.FileName;
                if (this.treeView1.Nodes.Count > 0)
                {
                    this.treeView1.Nodes.RemoveAt(0);
                }
                InitTreeData(file);
                this.ProjectPath = oBuliderXml.FileName.Replace(oBuliderXml.SafeFileName, "") ;
                //InitMainMenu(file);
            }
        }


        private void repositoryItemComboBoxDataType_SelectedValueChanged(object sender, EventArgs e)
        {
            this.repositoryItemComboBoxFormat.Items.Clear();
            if (!(modelView != null && modelView.Current != null && modelView.Current is FieldStutrc))
                return;
            string cellValue = ((DevExpress.XtraEditors.ComboBoxEdit)sender).EditValue.ToString();
            ((FieldStutrc)modelView.Current).DataType = cellValue;
            switch (cellValue)
            {
                case "String":
                    // string s = "Uppercase,Lowercase,Invisble,Unformatted";
                    string[] s1 = StringFormat.Split(',');
                    foreach (string ss in s1)
                    {
                        this.repositoryItemComboBoxFormat.Items.Add(ss);
                    }


                    break;
                case "Number":

                    foreach (string ss in NumberFormat.Split(','))
                    {
                        this.repositoryItemComboBoxFormat.Items.Add(ss);
                    }

                    //comboxCol.DataSource = s2.Split(',');
                    break;
                case "Date":

                    foreach (string ss in DateFormat.Split(','))
                    {
                        this.repositoryItemComboBoxFormat.Items.Add(ss);
                    }

                    break;
            }
            if(this.repositoryItemComboBoxFormat.Items.Count > 0 && this.repositoryItemComboBoxFormat.Items[0] != null)
                ((FieldStutrc)modelView.Current).Format = this.repositoryItemComboBoxFormat.Items[0].ToString();
        }

        #endregion

        #region 按钮事件
        private void button1_Click_1(object sender, EventArgs e)
        {
            //this.CreateLogicUnitXmlNode();
        }



        private void btnBulidCode_Click(object sender, EventArgs e)
        {
            string project = Fcbbas.CodeBuilder.JsonSerializer<Project>.DataContractToJson(this.CurProject);

            CreateFile(ProjectPath + "/" + CurProject.Name + ".prj", project, ".prj");

            //System.Data.DataSet ds = Fcdbas.CodeBuilder.XmlDatasetConvert.ConvertXMLFileToDataSet("D:\\Codeproj.xml");
            //var t = this.tableStutrc;
            this.logicUnit.CDBFile = string.IsNullOrEmpty(this.logicUnit.CDBFile)? AppDomain.CurrentDomain.BaseDirectory + "Template\\template.cdb":this.logicUnit.CDBFile;
            this.logicUnit.PKGFile = string.IsNullOrEmpty(this.logicUnit.PKGFile) ? AppDomain.CurrentDomain.BaseDirectory + "Template\\Template.pkg" : this.logicUnit.PKGFile;

            string _templateCDB = Fcdbas.Core.Util.FileHelper.GetFileContent(this.logicUnit.CDBFile);
            string _templatePKG = Fcdbas.Core.Util.FileHelper.GetFileContent(this.logicUnit.PKGFile);


            this.logicUnit = this.modelBS.DataSource as Fcdbas.CodeBuilder.TemplateCode.LogicUnit;
            this.logicUnit.FieldList = ((BindingSource)this.gridView1.DataSource).DataSource as IList<Fcdbas.CodeBuilder.TemplateCode.FieldStutrc>;

            _templateCDB = Fcdbas.CodeBuilder.TemplateCode.bTableStutrcTemplate.instace.TemplateReplace(_templateCDB, this.logicUnit);
            _templatePKG = Fcdbas.CodeBuilder.TemplateCode.bTableStutrcTemplate.instace.TemplateReplace(_templatePKG, this.logicUnit);

            //Fcdbas.CodeBuilder.TemplateCode.MySqlDbCdb entity = new Fcdbas.CodeBuilder.TemplateCode.MySqlDbCdb();
            //entity.InitTableStutrc(this.tableStutrc);
            //string t = entity.TransformText();
            CreateFile(ProjectPath + "/" + this.MoudleName + ".cdb", _templateCDB, ".cdb");
            //Fcdbas.CodeBuilder.TemplateCode.MySqlPackage _entity = new Fcdbas.CodeBuilder.TemplateCode.MySqlPackage();

            //_entity.InitTableStutrc(this.tableStutrc);
            //t = _entity.TransformText();
            CreateFile(ProjectPath + "/" + this.MoudleName + ".pkg", _templatePKG, ".pkg");

            //CreateLogicUnitXmlNode();

            MessageBox.Show("文件生成成功！請查看:" + ProjectPath + "/ 目錄下");
        }

        private void tNewProject_Click(object sender, EventArgs e)
        {

        }

        private void newProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewProject();
        }


        public string DefaultCDBFile
        {
            get;
            set;
        }

        public string DefaultPKGFile
        {
            get;
            set;
        }

        /// <summary>
        /// 新建项目
        /// </summary>
        private void NewProject()
        {
            if (this.treeView1.Nodes.Count > 0)
            {
                if (MessageBox.Show("Do you save the current project?", "Message", MessageBoxButtons.YesNo) == DialogResult.OK)
                {
                    SaveProject();
                }
                this.treeView1.Nodes.Clear();
            }

            Fcdbas.CodeBuilder.NewFile form = new Fcdbas.CodeBuilder.NewFile();
            form.Owner = this;
            if (DialogResult.OK == (form).ShowDialog())
            {
              //  TemplateDefault fmTmpDef = new TemplateDefault();
               // fmTmpDef.ShowDialog();

                NewProject(this.ProjectName);
                InitMainMenu();
                //MessageBox.Show(AppDomain.CurrentDomain.BaseDirectory);
            }
            this.CurProject.DefaultCDBFile = DefaultCDBFile;
            this.CurProject.DefaultPKGFile = DefaultPKGFile;
        }



        private void button1_Click(object sender, EventArgs e)
        {
            //Fcdbas.CodeBuilder.TemplateCode.TableStutrcTemplate entity = new Fcdbas.CodeBuilder.TemplateCode.TableStutrcTemplate();
            //entity.InitTableStutrc(txtFileName.Text);
            //string t = entity.TransformText();
        }


        #endregion

        private void saveProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveProject();
        }


        private void SaveProject()
        {
            string project = Fcbbas.CodeBuilder.JsonSerializer<Project>.DataContractToJson(this.CurProject);
            string projectXML = bTableStutrcTemplate.instace.Serialize(this.CurProject);
            SaveProject(project, ProjectPath + "/" + CurProject.Name + ".prj");
            CreateFile(ProjectPath + "/" + CurProject.Name + ".xml", projectXML, ".xml");

            MessageBox.Show("项目保存成功！請查看:" + ProjectPath + "/ 目錄下");
        }

        private void SaveProject(string project, string projectPath)
        {
            CreateFile(projectPath, project, ".prj");
        }

        private void BulidCodeFile(LogicUnit lu, string templateFile, string fileType)
        {
            if (lu.FieldList == null || lu.FieldList.Count == 0)
            {
                MessageBox.Show("当前逻辑单元尚未配置，请配置完整再生成！");
                return;
            }
            if (lu.FieldList.Where(p => p.pKey == "Y").Count() == 0)
            {
                MessageBox.Show("没有关键字，请配置完整再生成！");
                return;
            }
            if (lu.FieldList.Where(p => p.DataType == "String" && string.IsNullOrEmpty(p.Length)).Count() > 0)
            {
                MessageBox.Show("字符字段必须有长度，请配置完整再生成！");
                return;
            }

            if (lu.FieldList.Where(p => string.IsNullOrEmpty(p.DataType)).Count() > 0)
            {
                MessageBox.Show("数据类型不能为空，请配置完整再生成！");
                return;
            }


            string _templateFile = "";
            string _extendName;
            switch(fileType)
            {
                case "CDB":
                    _templateFile = string.IsNullOrEmpty(templateFile) ? cdbFile : templateFile;
                    _extendName = ".cdb";
                    break;
                case "PKG":
                    _templateFile = string.IsNullOrEmpty(templateFile) ? pkgFile : templateFile;
                    _extendName = ".pkg";
                    break;
                case "RPT":
                    _templateFile = string.IsNullOrEmpty(templateFile) ?  rptFile: templateFile;
                    _extendName = ".rpt";
                    break;
                case "WEB":
                    _templateFile = string.IsNullOrEmpty(templateFile) ? webFile : templateFile;
                    _extendName = ".web";
                    break;
                case "BSS":
                    _templateFile = string.IsNullOrEmpty(templateFile) ? bssFile : templateFile;
                    _extendName = ".bss";
                    break;
                default:
                    _templateFile = string.IsNullOrEmpty(templateFile) ? cdbFile : templateFile;
                    _extendName = ".cdb";
                    break;

            }
            string _templateContent = Fcdbas.Core.Util.FileHelper.GetFileContent(_templateFile);
            bTableStutrcTemplate template = new bTableStutrcTemplate();
            _templateContent = template.TemplateReplace(_templateContent, lu);
            CreateFile(ProjectPath + "/" + lu.LuName + _extendName, _templateContent, _extendName);
            MessageBox.Show("文件生成成功！請查看:" + ProjectPath + "/ 目錄下");
        }


        private void bulidCDBFileToolStripMenuItem_Click(object sender, EventArgs e)
        {

            BulidCodeFile(this.logicUnit, logicUnit.CDBFile, "CDB");
        }


        private void bulidPKGFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
             BulidCodeFile(this.logicUnit, logicUnit.PKGFile, "PKG");
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            NewProject();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            OpenProject();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            SaveProject();
        }

        private void cmsLogicUnit_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {

        }


    }
}
